package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ContactSummary;
import com.woyao.core.model.GetMyUserResponse;
import com.woyao.core.model.UserSummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class ReferActivity extends AppCompatActivity {
    ProgressDialog progressDialog;

    private ClipboardManager myClipboard;
    private ClipData myClip;

    private  Integer demand_id ;
    private  String demand_title ;
    private  String demand_desc ;
    private  Bitmap photo_bmp = null;

    private UserAdapter userAdapter;
    private RecyclerView referList = null;
    LinearLayoutManager referLayoutManager = null;

    private SearchView mSearchView;
    private TextView  demandTitle;
    private TextView  relationCount;


    private ContentResolver cr;

    private LinearLayout sendWechat;

    private String from = "";

    private Boolean contactsLoaded = false;

    static   Integer  CONTACTBOOK_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refer);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        referLayoutManager = new LinearLayoutManager(this);
        referLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        referList = (RecyclerView)findViewById(R.id.refer);
        referList.setLayoutManager(referLayoutManager);
        referList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        Intent intent = getIntent();
        demand_id =  intent.getIntExtra("id",8247);
        demand_title =  intent.getStringExtra("title");
        demand_desc =  intent.getStringExtra("description");

        byte buf[] = intent.getByteArrayExtra("photo_bmp");
        photo_bmp = BitmapFactory.decodeByteArray(buf, 0, buf.length);
//        photo_bmp = intent.getParcelableExtra("photo_bmp");



        this.setTitle("分享");

        demandTitle  = (TextView) findViewById(R.id.demandtitle_refer);

        demandTitle.setText(  demand_title  );

        relationCount  = (TextView) findViewById(R.id.myrelation_count);

        mSearchView = (SearchView) findViewById(R.id.refer_search);
//        mSearchView.setVisibility(View.GONE);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                loadCandidates(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        Button nextbtn = (Button) findViewById(R.id.refer_done);

        nextbtn.setVisibility(View.GONE);

        LinearLayout mobileContacts = (LinearLayout) findViewById(R.id.check_contactbook);

        mobileContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                tryGetContacts();
                Intent intent = new Intent();
                intent.setClass(ReferActivity.this, InviteActivity.class);
                startActivity(intent);
            }
        });

        LinearLayout copybtn = (LinearLayout) findViewById(R.id.copy_content);

        copybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayReferContent();
            }
        });

        LinearLayout browserbtn = (LinearLayout) findViewById(R.id.send_brower);

        browserbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("https://woyaooo.com/b/" + demand_id +"?rid=" + userId);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.setData(uri);
                startActivity(intent);
            }
        });


        LinearLayout contactbookbtn = (LinearLayout) findViewById(R.id.send_contactbook);

        contactbookbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(intent,
                        CONTACTBOOK_CODE);

            }
        });

        sendWechat = (LinearLayout) findViewById(R.id.send_wechat);
        sendWechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Bitmap photo_bmp = FileUtil.decodeSampledBitmapFromResource( getResources(),R.drawable.ic_launcher,20,20);
//                demand_title = "test";
                if  (demand_desc.length() >= 1000 ){
                    demand_desc = demand_desc.substring(0,999) ;
                }
                demand_desc = demand_desc.replace("\n","") ;
//                mImageView.setDrawingCacheEnabled(true);
//                Bitmap bitmap = Bitmap.createBitmap(mImageView.getDrawingCache());
//                mImageView.setDrawingCacheEnabled(false);
//                Common.shareWeb(ReferActivity.this, "wxae7ea097fe874f2c","https://woyaooo.com/b/" + demand_id + "?rid=" + userId,demand_title,demand_desc,photo_bmp);
            }
        });

        loadCandidates("refer:"+demand_id);
//        tryGetContacts();


    }

    private void displayReferContent() {
        final String text = demand_title + "\n" + demand_desc + "\nHttp://www.woyaooo.com/p/" + demand_id + "?rid=" + userId;

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("内容摘要").
                setMessage(text).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        myClip = ClipData.newPlainText("text", text);
                        myClipboard.setPrimaryClip(myClip);
                    }
                }).
                create();
        alertDialog.show();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("woyaooo","'已经授权'");
                    getContacts();

                } else {
                    Log.i("woyaooo","'没有授权'");

                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }


    public  void tryGetContacts() {
        contactsLoaded = true;

        if (ContextCompat.checkSelfPermission(ReferActivity.this,android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions( ReferActivity.this,
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    1);
            Log.i("woyaooo","'授权了吗？'");
        }else{
            getContacts();
        }




    }

    private void getContacts() {
        ArrayList<ContactSummary> contacts = new ArrayList<ContactSummary>();
        ArrayList<String> dups = new ArrayList<String>();
        try {

            cr = getContentResolver();
//            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cs = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null,  "sort_key", null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    try {
                        //拿到联系人id 跟name
                        int id = cs.getInt(cs.getColumnIndex("_id"));

                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number = number.replace(" ","").replace("+86","");

                        if (dups.contains( number ) ){
                            continue;
                        }
                        dups.add(number);
                        String name = cs.getString(cs.getColumnIndex("display_name"));



                        ContactSummary one = new ContactSummary();
                        one.setId(number);
                        one.setTitle(name  );
                        one.setDescription(number);
                        if (!one.getId().equals("") && !one.getTitle().equals("") && one.getId().length() == 11 && one.getId().startsWith("1") ){
                            contacts.add( one);
                        }

                        sb.append("displayname:" + name + ";");
                        sb.append("phone:" + number + ";");
                        sb.append("#");

                    }catch (Exception e){
                        Log.i("woyaooo", e.getMessage());
                    }
                }
                saveReload( sb.toString()) ;
//                Common.setProfileAttr("contacts", sb.toString());

            }

        }catch (Exception e){
            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }
    }


    public   void saveReload( final String content){
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"contacts",content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {

                if (success) {
                    loadCandidates("allusers" );
                } else {

                }
            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void loadCandidates( final  String keyword) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, GetMyUserResponse> task = new AsyncTask<Void, Void, GetMyUserResponse>() {
            @Override
            protected GetMyUserResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyUserResponse> responseCall = svc.getMyUser(userId,keyword);
                try {
                    GetMyUserResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final GetMyUserResponse response) {
                progressDialog.dismiss();
                if (response != null ) {
                    renderThem(response );

                    if (!keyword.equals("") && response.getContent().getItems().size() == 0) {
                        Toast.makeText(ReferActivity.this, response.getContent().getTitle(), Toast.LENGTH_LONG);
                    }

//                    if (response.getCondition().equals("askcontacts") && contactsLoaded == false){
//                        new AlertDialog.Builder(ReferActivity.this)
//                                .setTitle("请授权访问通信录")
//                                .setMessage("添加联系人为合作伙伴，需要访问通信录")
//                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        tryGetContacts();
//                                    }
//                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        }).create().show();
//                    }
                } else {
                    Common.showSnack(ReferActivity.this,referList,"网络错误，请重试");
                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }


    private  void renderThem( GetMyUserResponse response){
        List<UserSummary> users = response.getContent().getItems();

        userAdapter = new UserAdapter(this, users,"refer" );

        if (users.size() >0) {
            relationCount.setText( response.getContent().getTitle() );
        }else{
            relationCount.setText("没有合作");
        }

        referList.setAdapter(userAdapter);

        userAdapter.setChangedHandler(new UserAdapter.Changed() {
            @Override
            public void view(UserSummary r) {
                if (r.getId() > 0) {
                    Intent intent = new Intent();
                    intent.putExtra("id", r.getId());
                    intent.setClass(ReferActivity.this, PersonViewActivity.class);
                    startActivity(intent);
                }
            }
            public void act(UserSummary cs) {
                referUser(cs);
            }
        });
    }

    private void referUser( final UserSummary cs ) {

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.refer(userId,  demand_id,cs.getDemand_id());
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse ret) {

                if (ret != null) {
                    if (ret.isSuccess()) {
                        Toast.makeText(ReferActivity.this, "成功处理!", Toast.LENGTH_SHORT).show();

//                        Intent intent = new Intent();
//                        intent.setClass(thecontext, TalkActivity.class);
//                        intent.putExtra("mid", Integer.parseInt(ret.getMessage())  );
//                        thecontext.startActivity(intent);


                    }else{
                        Toast.makeText(ReferActivity.this, "处理失败了!", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if  (requestCode == CONTACTBOOK_CODE  ){

            Uri contactData = data.getData();
            String[] contact = this.getContactPhone(contactData);
//                clientName.setText(contact[0]);
////                phone.setText(contact[1]);

            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+ contact[1]));
            intent.putExtra("sms_body", contact[0] + "，分享一个业务合作机会，" +demand_title  + " woyaooo.com/b/" + demand_id + "");
            startActivity(intent);
//            refer(  contact[1]);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private String[] getContactPhone(Uri result) {



        String ColumnName = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
        String Columnphone = ContactsContract.CommonDataKinds.Phone.NUMBER;
        Cursor cursor = getContentResolver().query(result, null, null, null,
                null);
        cursor.moveToFirst();
        int columnNameIndex = cursor.getColumnIndex(ColumnName);
        int columnPhoneIndex = cursor.getColumnIndex(Columnphone);
        Log.i( "woyaooo","cursor.getColumnCount()：" + cursor.getColumnCount()); // 77 不同的手机不一样
        Log.i( "woyaooo","columnNameIndex：" + columnNameIndex); // 40
        Log.i( "woyaooo","columnPhoneIndex：" + columnPhoneIndex); // 27
        String[] res = new String[2];
        if (columnNameIndex > 0 && columnNameIndex < cursor.getColumnCount()) {
            String stringName = cursor.getString(columnNameIndex);
            res[0] = stringName;
        }
        if (columnPhoneIndex > 0 && columnPhoneIndex < cursor.getColumnCount()) {
            String stringPhone = cursor.getString(columnPhoneIndex);
            res[1] = stringPhone;
        }
        if (!cursor.isClosed()) {
            cursor.close();
        }
        return res;

    }


//    private void refer( final String  mobile) {
//
//        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
//            @Override
//            protected BaseResponse doInBackground(Void... params) {
//                ChanceService svc = ServiceFactory.get(ChanceService.class);
//                Call<BaseResponse> responseCall = svc.refer(userId,  demand_id,mobile,"");
//                try {
//                    BaseResponse r = responseCall.execute().body();
//                    return r;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(final BaseResponse ret) {
//
//                if (ret != null) {
//                    if (ret.isSuccess()) {
////                        Toast.makeText(ReferActivity.this, "成功处理!", Toast.LENGTH_SHORT).show();
//
//                    }else{
////                        Toast.makeText(thecontext, "处理失败了!", Toast.LENGTH_SHORT).show();
//                    }
//                }
//
//            }
//
//            @Override
//            protected void onCancelled() {
//
//            }
//        };
//        task.execute((Void) null);
//    }


//    private void finishRefer(){
//
//        Dialog alertDialog = new AlertDialog.Builder(ReferActivity.this).
//                setTitle("信息").
//                setMessage("完成介绍").
//                setIcon(R.drawable.ic_launcher).
//                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).
//                create();
//        alertDialog.show();
////        Common.alert(ReferActivity.this, "完成介绍");
////        finish();
//    }

}
